let router = {};
const ignores = ["login"];

const RouteHandler = {
	init(instance) {
		router = instance;
	},

	beforeRouteEnter(to, from, next) {
		//设置页面缓存
		from.meta.isKeepAlive = false;
		to.meta.isKeepAlive = true;
	},

	beforeRouteLeave(to, from, next) {
		//删除页面缓存 from.name是路由中name，也就是页面的路由名
		if (from.name && ignores.indexOf(from.name) === -1 && !from.meta.isKeepAlive) {
			let route = router.getRoutes().filter(route => route.name === from.name)[0];
			let instance = route.instances.default;
			if (instance.$vnode.parent && instance.$vnode.parent.componentInstance && instance.$vnode.parent.componentInstance.cache) {
				let defaultKey = instance.$vnode.componentOptions.Ctor.cid + (instance.$vnode.componentOptions.tag ? `::${instance.$vnode.componentOptions.tag}` : "");
				let key = instance.$vnode.key == null ? defaultKey : instance.$vnode.key;
				let cache = instance.$vnode.parent.componentInstance.cache;
				let keys = instance.$vnode.parent.componentInstance.keys;
				if (cache[key]) {
					if (keys.length) {
						let index = keys.indexOf(key);
						if (index > -1) {
							keys.splice(index, 1);
						}
					}
					delete cache[key];
				}
			}
			instance.$destroy();
		}
	},

	handleCacheData(to, from, next) {
		this.beforeRouteEnter(to, from, next);
		this.beforeRouteLeave(to, from, next);
		next();
	}
};
export default RouteHandler;
